<template>
  <div class="contract_manage_detail">
    <el-dialog width="70%" class="WholeScroll" :visible.sync="formShow" @close="handleClickDeal('cancel')" v-dialog-drag :modal-append-to-body="false" :close-on-click-modal="false" append-to-body>
      <span slot="title">
        <i class="iconfont icon-hetongguanli2"></i>
        <span>{{ title }}</span>
      </span>
      <div class="WholeScroll" style="max-height: 650px; overflow: auto">
        <el-form :model="formBaseData" ref="formBaseData" :rules="formBaseRules">
          <el-tabs v-model="activeName" @tab-click="handleClick">
            <el-tab-pane label="基本信息" name="first">

              <el-col :span="12">
                <el-form-item label="项目" prop="projectId" :label-width="formlabelWidth">
                  <el-select style="width: 100%" v-model="formBaseData.projectId" filterable placeholder="" :disabled="detailType === 'check'" @change="chooseProject(formBaseData.projectId)">
                    <el-option v-for="(item, i) in selectList.scopeProjects" :key="i" :label="item.proName" :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="合同分类" prop="type" :label-width="formlabelRightWidth">
                  <el-select style="width: 100%" v-model="formBaseData.type" filterable placeholder="" disabled>
                    <el-option v-for="(item, i) in selectList.type" :key="i" :label="item.label" :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="关联合同" :label-width="formlabelWidth">
                  <el-select style="width: 100%" v-model="formBaseData.oldContractId" filterable clearable placeholder="" :disabled="detailType === 'check' || detailType === 'approve' || (!formBaseData.projectId ) " @change="chooseContract(formBaseData.oldContractId)">
                    <el-option v-for="(item, i) in selectList.contractList" :key="i" :label="item.title" :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :span="24">
                <el-form-item ref="select" label="土建标" prop="sectionIds" :label-width="formlabelRightWidth">
                  <el-select style="width: 100%" v-model="formBaseData.sectionIds" filterable placeholder="" :disabled="detailType === 'check' " multiple :multiple-limit="formBaseData.sectionMutiSelect?99999:1">
                    <el-option v-for="(item, i) in selectList.sectionList" :key="item.id" :label="item.code" :disabled="!item.selectable" :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="合同编号" prop="number" :label-width="formlabelWidth">
                  <el-input class="contract_input" style="width: 100%" v-model="formBaseData.number" placeholder="" :disabled="detailType === 'check'  "></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="合同段名称" prop="numberName" :label-width="formlabelWidth">
                  <el-input class="contract_input" style="width: 100%" v-model="formBaseData.numberName" placeholder="" :disabled="detailType === 'check'  "></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="24">
                <el-form-item label="合同名称" prop="title" :label-width="formlabelRightWidth">
                  <el-input style="width: 100%" v-model="formBaseData.title" placeholder="" :disabled="detailType === 'check' "></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="合同总金额" prop="amount" :label-width="formlabelWidth">
                  <el-input class="contract_input" style="width: 100%" v-model="formBaseData.amount" @blur="blurInputEvent" type="number" @keydown.native="$publicJs.changeInputLimit" placeholder="" :disabled="detailType === 'check' ">
                    <template slot="append">万元</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="变更后合同总金额" prop="changeAmount" :label-width="formlabelWidth">
                  <el-input class="contract_input" style="width: 100%" v-model="formBaseData.changeAmount" @blur="blurInputEvent" type="number" @keydown.native="$publicJs.changeInputLimit" placeholder="" :disabled="detailType === 'check'">
                    <template slot="append">万元</template>
                  </el-input>
                </el-form-item>
              </el-col>

              <el-col :span="24">
                <el-form-item label="选择承包单位" prop="secondParty" :label-width="formlabelWidth">
                  <el-select style="width: 100%" v-model="formBaseData.secondParty" @change="changeSecondParty" :disabled="detailType === 'check' " filterable placeholder="">
                    <el-option v-for="(item, i) in selectList.companyListFiltered" :key="i" :label="item.fullname" :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :span="24">
                <el-form-item label="承包部名称" prop="contractManageDeptName" :label-width="formlabelRightWidth">
                  <el-input style="width: 100%" v-model="formBaseData.contractManageDeptName" placeholder="" :disabled="detailType === 'check'"></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="24">
                <!-- <el-form-item
                  label="承包单位履约人员"
                  prop="memberUids"
                  :label-width="formlabelWidth"
                >
                  <el-select
                    style="width: 100%"
                    v-model="formBaseData.memberUids"
                    filterable
                    filterable
                    placeholder=""
                    :disabled="detailType === 'check' || !formBaseData.secondParty"
                    multiple
                  >
                    <el-option
                      v-for="(item, i) in selectList.secondPartUserOpts"
                      :key="i"
                      :label="item.name"
                      :value="item.id"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>-->

                <el-form-item label="承包单位履约人员" :label-width="formlabelWidth">
                  <cmsPopoverTree :defaultProps="defaultProps" ref="cmsPopoverTree" :data="linkUserOpts" :selectVal="checkedLinkUsers" type="multi" @addMulTag="addMulTag" :defaultIds="defaultIds" @delTag="delTag" @addTag="addTag" :disabled="detailType === 'check' || !formBaseData.secondParty" />
                </el-form-item>

              </el-col>
              <el-col :span="12">
                <el-form-item label="合同负责人(乙方)" prop="principalOfSecondParty" :label-width="formlabelRightWidth">
                  <el-input style="width: 100%" v-model="formBaseData.principalOfSecondParty" placeholder="" :disabled="detailType === 'check' "></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="联系方式" prop="principalOfSecondPartyMobile" :label-width="formlabelRightWidth">
                  <el-input style="width: 100%" v-model="formBaseData.principalOfSecondPartyMobile" placeholder="" :disabled="detailType === 'check' || detailType === 'approve' "></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="收款账户" prop="payedCompanyName" :label-width="formlabelRightWidth">
                  <el-input style="width: 100%" v-model="formBaseData.payedCompanyName" placeholder="" :disabled="detailType === 'check' || detailType === 'approve' "></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="开户银行" prop="depositBank" :label-width="formlabelRightWidth">
                  <el-input style="width: 100%" v-model="formBaseData.depositBank" placeholder="" :disabled="detailType === 'check' || detailType === 'approve' "></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="账号" prop="bankAccount" :label-width="formlabelRightWidth">
                  <el-input style="width: 100%" v-model="formBaseData.bankAccount" placeholder="" :disabled="detailType === 'check' || detailType === 'approve' "></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="合同签订日期" prop="orderDate" :label-width="formlabelWidth">
                  <el-date-picker style="width: 100%" v-model="formBaseData.orderDate" type="date" format="yyyy-MM-dd" placeholder="选择合同签订日期" :disabled="detailType === 'check' ">
                  </el-date-picker>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="起始桩号" prop="initialPileNo" :label-width="formlabelWidth">
                  <el-input style="width: 100%" v-model="formBaseData.initialPileNo" placeholder="" :disabled="detailType === 'check'"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="结束桩号" prop="overPileNo" :label-width="formlabelRightWidth">
                  <el-input style="width: 100%" v-model="formBaseData.overPileNo" placeholder="" :disabled="detailType === 'check'"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="合同长度" prop="length" :label-width="formlabelWidth">
                  <el-input style="width: 100%" v-model="formBaseData.length" placeholder="" :disabled="detailType === 'check'" @blur="onNewNumber('length')">
                    <template slot="append">KM</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="合同工期" prop="duration" :label-width="formlabelRightWidth">
                  <el-input style="width: 100%" v-model="formBaseData.duration" placeholder="" :disabled="detailType === 'check'" @blur="onNewNumber('duration',0)">
                    <template slot="append">天</template>
                  </el-input>
                </el-form-item>
              </el-col>

              <el-col :span="24">
                <div class="formTitle">附件</div>
                <cmsFileTable ref="cmsFileTable" :buildUnitTable="buildUnitTable" :fileSystem="fileSystem" :detailId="detailId" :detailType="detailType" :buttonDelShow="buttonDelShow" :showNone="showNone" :buttonCheckShow="buttonCheckShow" :buttonUploadShow="buttonUploadShow" @change="tableChange">
                </cmsFileTable>
              </el-col>

            </el-tab-pane>

            <el-tab-pane label="合同金额维护" name="contractMoney">
              <el-row>
                <el-col :span="12">
                  <el-form-item label="暂列金" prop="provisionalSum" :label-width="formlabelWidth2">
                    <el-input style="width: 100%" v-model="formBaseData.provisionalSum" type="number" @keydown.native="$publicJs.changeInputLimit" placeholder="" :disabled="detailType === 'check'">
                      <template slot="append">万元</template>
                    </el-input>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row>
                <el-col :span="12">
                  <el-form-item label="变更增减暂列金" prop="modifyProvisionalSum" :label-width="formlabelWidth2">
                    <el-input style="width: 100%" v-model="formBaseData.modifyProvisionalSum " type="number" @keydown.native="$publicJs.changeInputLimit" placeholder="" :disabled="detailType === 'check'">
                      <template slot="append">万元</template>
                    </el-input>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row>
                <el-col :span="12">
                  <el-form-item label="安全生产费" prop="safetyMoney" :label-width="formlabelWidth2">
                    <el-input style="width: 100%" v-model="formBaseData.safetyMoney " type="number" @keydown.native="$publicJs.changeInputLimit" placeholder="" :disabled="detailType === 'check'">
                      <template slot="append">万元</template>
                    </el-input>
                  </el-form-item>
                </el-col>
              </el-row>

            </el-tab-pane>

          </el-tabs>
        </el-form>
      </div>

      <div slot="footer" class="dialog-footer">
        <!--api操作按钮 除去上报-->
        <!--新建和编辑的暂存上报-->
        <template v-if="detailType === 'build' || detailType === 'edit'">
          <el-button size="small" type="primary" :loading="isLoading" @click="handleClickDeal('submit', { flag: 1 })"><i class="iconfont icon-icon_save"></i> 确 定
          </el-button>
        </template>
        <el-button size="small" @click="handleClickDeal('cancel')"><i class="iconfont icon-icon_cancel"></i> 取 消
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import cmsPopoverTree from '@/views/components/cmsPopoverTree.vue'
import crudProject from '@/api/buss/project'
import dept from '@/api/system/dept'
import msgUtil from '@/utils/msgUtil'
import crudDict from '@/api/system/dict'
import mainline from '@/api/buss/mainlineContract'
import { getOneVO, getProjectSection, getRelatedContractList } from "../../../../api/buss/mainlineContract";


export default {
  name: 'contractorContract-detail',
  components: {
    cmsPopoverTree,

  },
  props: {
    postDetail: {
      type: Object,
      default: {
        show: false,
        type: 'build',
        params: {}
      }
    }
  },
  watch: {
    postDetail(value) {
      console.log(value)
      // 显示详情弹窗
      this.formShow = value.show
      // 初始化窗口参数
      this.activeName = 'first'
      // 详情类型
      this.detailType = value.type
      this.buildUnitTable = [
        {
          stuffName: '合同文本',
          part: "partOne",
          file: [{ realName: '' }],
          isNeed: false,
          loading: false,
          isMulti: true
        },
        {
          stuffName: '其他',
          file: [{ realName: '' }],
          part: "other",
          isNeed: false,
          loading: false,
          isMulti: true
        },
      ],




        // 详情id
        //this.detailId = value.params === undefined ? 0 : value.params.detailId
        this.detailId = value.detailId ? value.detailId : '';
      this.intiData()

      if (this.detailType !== 'build') {
        // 获取详情请求
        this.getDetail()
        if (this.detailType == "check") {
          this.title = "查看合同"
        }
        if (this.detailType == "edit") {
          this.title = "编辑合同"
        }
      }
      if (this.detailType === 'build') {
        this.title = "新增合同"

        // 获取编号
        this.getScopeProjects("")
      }


    }
  },
  data() {
    return {
      linkUsers: {},
      ownerRepresentativeUsers: {},
      ownerRepresentativeUserOpts: [],
      linkUserOpts: [],
      checkedLinkUsers: [],
      defaultIds: [],
      defaultProps: {
        children: 'children',
        label: 'name',
      },



      contractTypeName: '',
      isLoading: false,
      detailType: 'build', // 详情类型 build新建 check不可编辑查看 edit编辑
      detailId: '', // 当前详情的id
      formShow: false, // 表单展示
      formlabelWidth: '150px', // 表单左侧标题宽度
      formlabelRightWidth: '150px', // 表单左侧标题宽度
      formlabelWidth2: '180px', // 表单左侧标题宽度
      title: '新增合同',
      activeName: 'first',
      // 所有下拉框列表的集合
      selectList: {
        //所有合同
        contractList: [],

        //类型
        type: [
          {
            label: '全部',
            value: '0'
          }
        ], // 关联标段
        sectionList: [
          {
            label: '全部',
            value: '0'
          }
        ], // 阶段
        //公司列表
        companyList: [],
        //  公司列表根据类型过滤后的结果
        companyListFiltered: [],
        //  可以选择的项目列表
        scopeProjects: [],
        file: [], // 文件
        //  标段负责人选择项
        secondPartUserOpts: [],
        //  甲方标段管理人选择项
        firstPartUserOpts: [],
      },
      // 表单基本信息内容
      formBaseData: {
        oldContractId: '',
        memberUids: [],
        sectionIds: [],
        sectionMutiSelect: false,
        //合同信息
        number: '',
        numberName: '',
        title: '',
        amount: '',
        changeAmount: '',
        type: '',
        secondParty: '',
        initialPileNo: '',
        length: '',
        principalOfSecondParty: '',
        principalOfSecondPartyMobile: '',
        payedCompanyName: '',
        depositBank: '',
        bankAccount: '',
        contractManageDeptName: '',
        overPileNo: '',
        duration: '',
        totalPrepaid: '',
        startingPointToDeduct: '',
        deductedRateForMaterials: '',
        startingPointToKickback: '',
        allListMoney: '',
        engineeringPremium: '',
        managementCost: '',
        areamoney: '',
        designExpense: '',
        orderDate: '',
      },
      // 表单基本信息验证
      formBaseRules: {
        oldContractId: [{
          required: true, message: '请选择关联合同', trigger: 'blur'
        }],
        projectId: [{
          required: true, message: '请选择项目', trigger: 'blur'
        }],
        sectionIds: [{
          required: true, message: '请选择土建标', trigger: 'blur'
        }],
        secondParty: [{ required: true, message: '请选择承包单位', trigger: 'blur' }],
        number: [
          { required: true, message: '请输入' + '合同编号', trigger: 'blur' }
        ],
        numberName: [
          { required: true, message: '请输入' + '合同段编号', trigger: 'blur' }
        ],
        title: [
          { required: true, message: '请输入' + '合同名称', trigger: 'blur' }
        ],
        amount: [
          { required: true, message: '请输入' + '合同总金额', trigger: 'blur' }
        ],
        changeAmount: [
          { required: true, message: '请输入' + '变更后合同总金额', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择' + '合同类型', trigger: 'change' }
        ],

        secondParty: [
          {
            required: true,
            message: '请选择' + '合同签订单位(乙方)',
            trigger: 'change'
          }
        ],
        principalOfSecondParty: [
          {
            required: true,
            message: '请输入' + '合同负责人(乙方)',
            trigger: 'blur'
          }
        ],


        // principalOfSecondPartyMobile: [
        //   {
        //     required: true,
        //     message: '请输入' + '联系方式',
        //     trigger: 'blur'
        //   }
        // ],


        contractManageDeptName: [
          {
            required: true,
            message: '请填写' + '乙方承包商名称',
            trigger: 'change'
          }
        ],


        /*  memberUids: [
            {
              required: true,
              message: '请选择' + '承包单位履约人员',
              trigger: 'blur'
            }
          ],*/
        consMemberUids: [
          {
            required: false,
            message: '请选择' + '甲方单位参与人',
            trigger: 'change'
          }
        ],
        // payedCompanyName: [{
        //   required: true,
        //   message: '请填写收款账户',
        //   trigger: 'blur'
        // }],
        // depositBank: [{
        //   required: true,
        //   message: '请填写开户银行',
        //   trigger: 'blur'
        // }],
        // bankAccount: [{
        //   required: true,
        //   message: '请填写账号',
        //   trigger: 'blur'
        // }]
      },
      //  允许标段选择项
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      //  是否需要出现标段
      enableSection: false,
      //  是否需要选择是否总承包
      enableWhetherManageSelection: false,
      showList: false,
      buildUnitTable: [
        {
          stuffName: '合同文本',
          part: "partOne",
          file: [{ realName: '' }],
          isNeed: false,
          loading: false,
          isMulti: true
        },
        {
          stuffName: '其他',
          file: [{ realName: '' }],
          part: "other",
          isNeed: false,
          loading: false,
          isMulti: true
        },
      ],
      fileSystem: {
        attachId: {
          partOne: '',
          partTwo: '',
          partThree: '',
          partFour: '',
          other: '',
          taohong: ''
        },
        sys: 'buss',
        module: 'contractorContract',
        entityClass: 'contractorContract',
        viewByAnon: true,
        longLife: false,
        part: {
          partOne: 'partOne',
          partTwo: 'partTwo',
          partThree: 'partThree',
          partFour: 'partFour',
          other: "other",
        },
      },

    }
  },

  filters: {
    moneyFilter(value) {
      try {
        let before = value.toFixed(2)
        before = before.toString()
        let num = before.split('.')[0]
        let numSmall = before.split('.')[1]
        let result = [],
          counter = 0
        num = (num || 0).toString().split('')
        for (let i = num.length - 1; i >= 0; i--) {
          counter++
          result.unshift(num[i])
          if (!(counter % 3) && i != 0) {
            result.unshift(',')
          }
        }
        let after =
          numSmall === undefined
            ? result.join('')
            : result.join('') + '.' + numSmall
        return after
      } catch (e) {
        return ''
      }
    }
  },
  created() {
  },
  methods: {
    onNewNumber(str, num) {
      let digit = 2
      if (num !== undefined) { digit = num }
      if (Number(this.formBaseData[str])) {
        this.formBaseData[str] = Number(this.formBaseData[str]).toFixed(digit)
      } else {
        this.$set(this.formBaseData, str, '')
      }
    },
    getLinkUserOpts(compId) {
      this.linkUserOpts = []
      this.checkedLinkUsers = []
      crudProject.getlinkUsersDept(compId).then(res => {
        if (res.status === 1) {
          let linkUserOpts = res.data;
          this.linkUserOpts = linkUserOpts;
          let ownerRepresentativeUserOpts = res.data;
          this.ownerRepresentativeUserOpts = ownerRepresentativeUserOpts;
          console.log(res.data, '俏丽吗++++++++++++++++++++++++++')
          this.collectDeptUserById(linkUserOpts);
          this.collectDeptUserCompById(ownerRepresentativeUserOpts);
          this.$forceUpdate();
        } else {
          //this.$messageError(res.data.message)
          msgUtil.error2(res.data.message)
        }
      }).catch(res => {
        console.log('请求出现错误', res);
        msgUtil.error2('获取部门用户列表失败!')
      })
    },

    getLinkUserOptss(compId) {
      return crudProject.getlinkUsersDept(compId).then(res => {
        if (res.status === 1) {
          let linkUserOpts = res.data;
          //if(this.detailType != 'edit'){
          this.linkUserOpts = linkUserOpts;
          //}
          let ownerRepresentativeUserOpts = res.data;
          this.ownerRepresentativeUserOpts = ownerRepresentativeUserOpts;
          console.log(res.data, '俏丽吗++++++++++++++++++++++++++')
          this.collectDeptUserById(linkUserOpts);
          this.collectDeptUserCompById(ownerRepresentativeUserOpts);
          return new Promise(reslove => {
            reslove(res)
          })
          this.$forceUpdate();
        } else {
          //this.$messageError(res.data.message)
          msgUtil.error2(res.data.message)
        }
      }).catch(res => {
        console.log('请求出现错误', res);
        msgUtil.error2('获取部门用户列表失败!')
      })
    },

    collectDeptUserById(linkUserOpts) {
      for (let i = 0; i < linkUserOpts.length; i++) {
        let user = linkUserOpts[i]
        let id = user.id
        let children = user.children
        this.linkUsers[id] = user
        if (children && children.length > 0) {
          this.collectDeptUserById(children)
        }
      }
    },

    collectDeptUserCompById(ownerRepresentativeUserOpts) {
      for (let i = 0; i < ownerRepresentativeUserOpts.length; i++) {
        let user = ownerRepresentativeUserOpts[i]
        let id = user.id
        let children = user.children

        this.ownerRepresentativeUsers[id] = user
        if (children && children.length > 0) {
          this.collectDeptUserCompById(children)
        }
      }
    },

    /**
     *  -----@addMulTag="addMulTag"
     * 多选增加--多选模式使用
     * @param val
     */
    addMulTag(val) {
      console.log(val)
      // this.checkedLinkUsers.splice(0, this.checkedLinkUsers.length)
      this.checkedLinkUsers = []
      val.forEach((item) => {
        this.checkedLinkUsers.push(item)
      })
      this.$forceUpdate()
    },
    /**
     * 删除会签部门人
     */
    delTag(val) {
      this.checkedLinkUsers.splice(val, 1)

      this.$forceUpdate()
      this.$refs.cmsPopoverTree.updateTree()
      this.$refs.cmsPopoverTree.$forceUpdate()
    },
    /**
     * 增加会签人
     * @param val
     */
    addTag(val) {
      this.checkedLinkUsers.push(val)
      this.$refs.cmsPopoverTree.updateTree()
      this.$refs.cmsPopoverTree.$forceUpdate()
      this.$forceUpdate()
    },




    intiData() {
      this.selectList.type = []
      crudDict.getByCode('MContractType').then(res => {
        if (res.code === 200) {
          var data = res.data;
          var typeId = ""
          for (var i in data) {
            if (data[i].name == "施工合同") {
              typeId = data[i].id
            }
            this.selectList.type.push({ 'value': data[i].id, 'label': data[i].name });
          }
          this.formBaseData.type = typeId
          this.contractTypeName = "施工合同"
          this.formBaseData.sectionMutiSelect = true
        } else {
          msgUtil.error2(res.data.message)
        }
      }).catch(() => {
        msgUtil.error2("获取问题归属失败")
      })

      dept.listForSys("").then(res => {
        this.selectList.companyList = []
        if (res.code === 200) {
          res.data.forEach((item) => {
            this.$set(
              this.selectList.companyList,
              this.selectList.companyList.length,
              item
            )
          })

          if (this.contractTypeName = "施工合同") {
            this.selectList.companyListFiltered = this.selectList.companyList.filter(cp => {
              if (cp.typeName) {
                return cp.typeName.indexOf("施工单位") != -1
              }
            });
          }
        } else {
          msgUtil.error2(res.data.message)
        }
      })
    },

    getScopeProjects(id) {
      mainline.getScopeProjects(id).then(res => {
        if (res.status === 1) {
          this.selectList.scopeProjects = res.data
        } else {
          msgUtil.error2(res.data.message)
        }
      }).catch(res => {
        console.log('请求出现错误', res);
        msgUtil.error2('获取项目列表失败!')
      })
    },

    getProjectSection(projectId) {
      return mainline.getProjectSection(projectId, this.detailId, this.formBaseData.type).then(res => {
        if (res.status === 1) {
          this.selectList.sectionList = []
          //this.selectList.sectionList = res.data
          return new Promise(reslove => {
            reslove(res)
          })
        } else {
          msgUtil.error2(res.data.message)
        }
      }).catch(res => {
        console.log('请求出现错误', res);
        msgUtil.error2('获取标段列表失败!')
      })
    },


    getRelatedContractList(projectId, typeName) {
      mainline.getRelatedContractList(projectId, typeName).then(res => {
        if (res.status === 1) {
          this.selectList.contractList = res.data
        } else {
          msgUtil.error2(res.data.message)
        }
      }).catch(res => {
        console.log('请求出现错误', res);
        msgUtil.error2('获取关联合同列表失败!')
      })
    },


    //选择项目
    chooseProject(projectId) {
      this.formBaseData.oldContractId = ''
      this.formBaseData.number = ''
      this.formBaseData.numberName = ''
      this.secondPartyNoRelationName = ''
      this.principalOfSecondParty = ''
      this.principalOfSecondPartyMobile = ''
      this.formBaseData.payedCompanyName = ''
      this.formBaseData.depositBank = ''
      this.formBaseData.bankAccount = ''
      this.formBaseData.amount = ''
      this.formBaseData.orderDate = ''
      this.formBaseData.sectionIds = []
      this.formBaseData.memberUids = []
      this.checkedLinkUsers = []
      this.formBaseData.secondParty = ''
      this.formBaseData.contractManageDeptName = ''
      this.formBaseData.title = ''
      this.formBaseData.changeAmount = ''
      this.formBaseData.principalOfSecondParty = ''
      this.formBaseData.principalOfSecondPartyMobile = ''
      this.formBaseData.initialPileNo = ''
      this.formBaseData.overPileNo = ''
      this.formBaseData.length = ''
      this.formBaseData.duration = ''

      this.getRelatedContractList(projectId, this.contractTypeName)
      //this.getProjectSection(projectId)
      this.getProjectSection(projectId).then(res => {
        res.data.forEach(item => {
          this.selectList.sectionList.push(item)
        })
      })

    },

    //选择关联合同
    chooseContract(contractId) {
      this.formBaseData.contractManageDeptName = ''
      this.formBaseData.sectionIds = []
      this.formBaseData.number = ''
      this.formBaseData.numberName = ''
      this.formBaseData.title = ''
      this.formBaseData.amount = ''
      this.formBaseData.changeAmount = ''

      this.formBaseData.secondParty = ''
      this.formBaseData.memberUids = []
      this.checkedLinkUsers = []
      this.formBaseData.secondPartyNoRelationName = ''
      this.formBaseData.principalOfSecondParty = ''
      this.formBaseData.principalOfSecondPartyMobile = ''
      this.formBaseData.payedCompanyName = ''
      this.formBaseData.depositBank = ''
      this.formBaseData.bankAccount = ''
      this.formBaseData.orderDate = ''

      this.selectList.contractList.forEach(item => {
        if (item.id == contractId) {
          this.formBaseData.contractManageDeptName = item.contractManageDeptName
          this.formBaseData.number = item.number
          this.formBaseData.title = item.title
          this.formBaseData.amount = item.amount
          this.formBaseData.changeAmount = item.changeAmount
          this.formBaseData.secondPartyNoRelationName = item.secondPartyNoRelationName
          this.formBaseData.principalOfSecondParty = item.principalOfSecondParty
          this.formBaseData.principalOfSecondPartyMobile = item.principalOfSecondPartyMobile
          this.formBaseData.payedCompanyName = item.payedCompanyName
          this.formBaseData.depositBank = item.depositBank
          this.formBaseData.bankAccount = item.bankAccount
          this.formBaseData.changeAmount = item.changeAmount
          this.formBaseData.orderDate = item.orderDate
        }
      })
    },

    blurInputEvent() {
      if (this.formBaseData.amount) {
        this.formBaseData.amount = Number(this.formBaseData.amount)
      }
      if (this.formBaseData.changeAmount) {
        this.formBaseData.changeAmount = Number(this.formBaseData.changeAmount)
      }
    },


    changeSecondParty() {
      this.formBaseData.memberUids = []
      this.checkedLinkUsers = []

      let obj = {}
      this.selectList.companyListFiltered.forEach(item => {
        if (item.id == this.formBaseData.secondParty) {
          obj = item
        }
      })

      this.formBaseData.contractManageDeptName = obj.fullname
      this.$forceUpdate()

      //this.getSecondPartUserTree()
      this.getLinkUserOpts(obj.id)
    },

    /**
     * 获取乙方单位参与人
     * */
    getSecondPartUserTree() {
      mainline.getSecondPartUserTree(this.formBaseData.secondParty).then(res => {
        if (res.status === 1) {
          this.selectList.secondPartUserOpts = res.data
        } else {
          msgUtil.error2(res.data.message)
        }
      }).catch(res => {
        console.log('请求出现错误', res);
        msgUtil.error2('获取履约人员列表失败!')
      })
    },


    // 获取详情请求 api
    getDetail() {

      mainline.getOneVO(this.detailId).then(res => {
        if (res.status == 1) {

          let formBaseData = res.data;
          this.selectList.sectionList = []
          let sectionIds = res.data.sectionIds
          this.formBaseData.type = res.data.type
          this.formBaseData.secondParty = res.data.secondParty

          this.getScopeProjects(res.data.applyUser)
          this.getRelatedContractList(res.data.projectId, this.contractTypeName)


          let linkUsers = formBaseData.linkUsers
          this.formBaseData.linkUsers = linkUsers

          this.getLinkUserOptss(res.data.secondParty).then(res => {
            if (linkUsers) {
              let linkUserIds = formBaseData.linkUsers.split(',')
              let checkedLinkUsers = []
              for (let i = 0; i < linkUserIds.length; i++) {
                let linkUser = this.linkUsers[linkUserIds[i]]
                if (linkUser) {
                  checkedLinkUsers.push(linkUser)

                }
              }
              this.$set(this, 'checkedLinkUsers', checkedLinkUsers)
              //this.checkedLinkUsers = checkedLinkUsers
            } else {
              this.$set(this, 'checkedLinkUsers', [])
              //this.checkedLinkUsers = []
            }
          })


          //this.getSecondPartUserTree()

          this.formBaseData.id = res.data.id
          this.formBaseData = JSON.parse(JSON.stringify(res.data))
          this.formBaseData.sectionMutiSelect = true
          this.formBaseData.orderDate = res.data.orderDates
          this.getProjectSection(res.data.projectId).then(res => {

            res.data.forEach(item => {
              this.selectList.sectionList.push(item)
            })
          })
          this.formBaseData.sectionIds = sectionIds
        } else {
          msgUtil.error2(res.data.message)
        }
      }).catch(() => {
        msgUtil.error2("获取详情信息失败")
      })

    },


    // 提交详情 提交1/暂存0 新建0/修改1
    submitDetail(type, callback) {
      let linkUserIds = []
      let checkedLinkUsers = this.checkedLinkUsers
      if (checkedLinkUsers.length > 0) {
        for (let i = 0; i < checkedLinkUsers.length; i++) {
          linkUserIds.push(checkedLinkUsers[i].id)
        }
      }
      this.formBaseData.memberUids = linkUserIds
      this.formBaseData.linkUsers = linkUserIds.join(',')

      this.formBaseData.id = this.detailId
      this.formBaseData.secondPartyRelation = true
      this.formBaseData.contractManaged = true
      this.formBaseData.mainlineContractType = 1
      if (this.detailType === 'build') {
        mainline.submit(this.formBaseData).then(res => {
          if (res.status === 1) {
            this.detailId = res.data.id
            //this.saveFiles()
            //this.isLoading = false
            this.$notify({
              title: '数据修改成功',
              type: 'success',
              duration: 1500
            })
            this.saveFiles()
            // 传值给父组件刷新列表
            this.$emit('reloadList')
            this.formShow = false

          } else {
            msgUtil.error2(res.data.message)
          }
        }).catch((response) => {
          this.$notify({
            title: '数据表新增失败',
            type: 'error',
            duration: 2500
          })
        }).finally((response) => {
          this.isLoading = false
        })
      } else {
        mainline.resubmit(this.formBaseData).then(res => {
          if (res.status === 1) {
            this.detailId = res.data.id
            // this.saveFiles()
            //this.isLoading = false
            this.$notify({
              title: '数据修改成功',
              type: 'success',
              duration: 1500
            })
            this.saveFiles()
            // 传值给父组件刷新列表
            this.$emit('reloadList')
            this.formShow = false

          } else {
            msgUtil.error2(res.data.message)
          }
        }).catch((response) => {
          this.$notify({
            title: '数据表新增失败',
            type: 'error',
            duration: 2500
          })
        }).finally((response) => {
          this.isLoading = false
        })
      }

    },

    // 点击各个流程的按钮事件
    handleClickDeal(type, res) {
      console.log(type, res)
      switch (type) {
        // 取消，关闭窗口
        case 'cancel':
          // 重置表单验证
          if (this.$refs['formBaseData']) {
            this.$refs['formBaseData'].resetFields()
          }
          //清空表单内容
          this.formBaseData = {
            oldContractId: '',
            memberUids: [],
            sectionIds: [],
            sectionMutiSelect: false,
            //合同信息
            number: '',
            numberName: '',
            title: '',
            amount: '',
            changeAmount: '',
            type: '',
            secondParty: '',
            initialPileNo: '',
            length: '',
            principalOfSecondParty: '',
            principalOfSecondPartyMobile: '',
            payedCompanyName: '',
            depositBank: '',
            bankAccount: '',
            contractManageDeptName: '',
            overPileNo: '',
            duration: '',
            totalPrepaid: '',
            startingPointToDeduct: '',
            deductedRateForMaterials: '',
            startingPointToKickback: '',
            allListMoney: '',
            engineeringPremium: '',
            managementCost: '',
            areamoney: '',
            designExpense: '',
            orderDate: '',

          } // 表单基本信息内容
          // 清空文件
          this.selectList.file = []

          this.linkUsers = {}
          this.ownerRepresentativeUsers = {}
          this.ownerRepresentativeUserOpts = []
          this.linkUserOpts = []
          this.checkedLinkUsers = []
          this.defaultIds = []

          this.selectList.companyList = []
          this.selectList.companyListFiltered = []
          this.selectList.scopeProjects = []
          this.selectList.secondPartUserOpts = []
          this.selectList.firstPartUserOpts = []
          this.selectList.sectionList = []
          // 关闭弹窗
          this.formShow = false
          this.enableWhetherManageSelection = false
          this.detailId = ''
          break
        // 保存
        case 'submit':
          let flag = res.flag
          // 表单验证
          this.$refs['formBaseData'].validate((valid) => {
            if (valid) {
              this.isLoading = true
              // 提交详情
              this.submitDetail(flag, () => {
                this.saveFiles()
              })
            } else {
              this.isLoading = false
            }
          })
          break
        // 删除

      }
    },

    saveFiles() {
      this.$refs['cmsFileTable'].bindAllFile(this.detailId)
    },



    handleClick(name, action) {

    },


    /**
     *显示删除按钮
     * @param row
     */
    buttonDelShow(row) {
      let flag = false
      if ((this.detailType === 'build' || this.detailType === 'edit') && row.file[0].realName !== '' && !row.isNeed) {
        flag = true
      }
      // 经办人操作时
      // if ((this.detailType!=='build'&&this.detailType!=='edit'&&this.detailType!=='check')&&this.isReport&&row.file[0].realName!==''&&!row.isNeed) {
      //   flag=true
      // }
      // 多文件上传的控制的控制
      if (row.isMulti) {
        flag = false
      }
      return flag;
    },
    /**
     *控制显示暂无文件
     * @param row
     */
    showNone(row) {
      let flag = false
      if ((this.detailType !== 'build' && this.detailType !== 'edit') && row.file[0].realName === '') {
        flag = true
      }
      // 经办人操作时
      // if ((this.detailType!=='build'&&this.detailType!=='edit'&&this.detailType!=='check')&&this.isReport) {
      //   flag=false
      // }
      return flag
    },
    /**
     * 控制查看按钮显示
     * @param row
     */
    buttonCheckShow(row) {
      let flag = false
      if ((this.detailType !== 'build' && this.detailType !== 'edit') && row.file[0].realName !== '') {
        flag = true
      }
      // 经办人操作时
      // if ((this.detailType!=='build'&&this.detailType!=='edit'&&this.detailType!=='check')&&this.isReport) {
      //   flag=false
      // }
      // 多文件上传的控制的控制
      if (row.isMulti) {
        flag = false
      }
      return flag
    },
    /**
     * 控制上传按钮显示
     * @param row
     * @returns {boolean}
     */
    buttonUploadShow(row) {
      let flag = false
      if (this.detailType === 'build' || this.detailType === 'edit') {
        flag = true
      }
      // 经办人操作时
      // if ((this.detailType!=='build'&&this.detailType!=='edit'&&this.detailType!=='check')&&this.isReport) {
      //   flag=true
      // }
      return flag
    },
    tableChange(val) {
      this.$set(this, 'buildUnitTable', [...val])
    },


    moneyFilter(value) {
      try {
        let before = value.toFixed(2)
        before = before.toString()
        let num = before.split('.')[0]
        let numSmall = before.split('.')[1]
        let result = [],
          counter = 0
        num = (num || 0).toString().split('')
        for (let i = num.length - 1; i >= 0; i--) {
          counter++
          result.unshift(num[i])
          if (!(counter % 3) && i != 0) {
            result.unshift(',')
          }
        }
        let after =
          numSmall === undefined
            ? result.join('')
            : result.join('') + '.' + numSmall
        return after
      } catch (e) {
        return ''
      }
    },


  }
}
</script>

<style scoped lang="scss">
.el-select.half {
  width: 250px;
}

.el-select.fill {
  width: 800px;
}

.contract_input {
  width: 250px;
}

.contract_input2 {
  width: 240px;
}

.el-input .el-select {
  width: 130px;
}

.fee_add {
  color: #008fe0;
  border-color: #008fe0;
  float: right;
  margin-bottom: 10px;
}
</style>
